package com.fowo.api.common.mybatis.interceptor;

import com.fowo.api.common.mybatis.helper.MybatisSqlHelper;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 为所有 MyBatis 方法操作添加名为 sqlHelper 的组件参数
 * @author yl_ls
 */
@Intercepts({
        @Signature(method = "query",
                args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class},
                type = Executor.class),
        @Signature(method = "query",
                args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class},
                type = Executor.class),
})
public class SqlHelperInterceptor implements Interceptor {
    @Resource
    private MybatisSqlHelper sqlHelper;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (invocation.getTarget() instanceof Executor) {
            addSqlHelperArg(invocation);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    private void addSqlHelperArg(Invocation invocation) {
        Object parameterObject = invocation.getArgs()[1];
        if (parameterObject instanceof Map) {
            ((Map<String, Object>) parameterObject).put("sqlHelper", sqlHelper);
        }
    }
}
